<?php
/*
 *  avisaro wlan modul 2.0 command line tools
 *  Copyright (C) 2009 Daniel Werner, Mark Schmale
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

class cliParser 
{
    public static function parse($line)
    {
        //////
        // at first, we gonna find some strings
        $len    = strlen($line);
        $in_str = false;
        $start  = 0;
        for($i=0;$i<$len;$i++)
        {
            if($line[$i] == '"' || $line[$i] == '\'')
            {
                if($in_str == false)
                {
                    $in_str = true;
                    $start  = $i;
                } else if($line[$start] == $line[$i]) {
                    $in_str    = false;
                    $strings[] = array($start, $i);
                }
            }
        }
        //////
        // replace strings by identifieres
        if(is_array($strings))
        {
            foreach($strings as $k => $string)
            {
                list($start, $end) = $string;
                $len          = $end-$start;
                $content      = substr($line, $start+1, $len-1);
                $id           = 'T_STRING_'.$k;
                $pre_tok[$id] = $content;
                $line         = substr_replace($line, '"'.$id.'"', $start, $len+1); 
            }
        }
        $ttr = explode('&&', $line);
        foreach($ttr as $run)
        {
            $run    = trim($run);
            $params = explode(' ', $run);
            if(is_array($pre_tok))
            {
                foreach($params as $k => $v)
                {
                    $params[$k] = str_replace(array_keys($pre_tok), array_values($pre_tok), $v);
                }
            }
            $cmd    = array_shift($params);
            $parts  = array(  'cmd'   => $cmd
                            , 'param' => $params);
            $commands[] = $parts;
        }
        return $commands;
    }

}
